package com.gr.smartedubackend.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gr.smartedubackend.common.BusinessException;
import com.gr.smartedubackend.common.ErrorCode;
import com.gr.smartedubackend.constant.CommonConstant;
import com.gr.smartedubackend.model.dto.student.StudentQueryByTeacherDto;
import com.gr.smartedubackend.model.dto.student.StudentQueryRequest;
import com.gr.smartedubackend.model.dto.student.StudentUpdateRequest;
import com.gr.smartedubackend.model.entity.Student;
import com.gr.smartedubackend.model.entity.StudentGroup;
import com.gr.smartedubackend.model.entity.Teacher;
import com.gr.smartedubackend.model.entity.TeachingSchedule;
import com.gr.smartedubackend.service.StudentGroupService;
import com.gr.smartedubackend.service.StudentService;
import com.gr.smartedubackend.mapper.StudentMapper;
import com.gr.smartedubackend.service.TeacherService;
import com.gr.smartedubackend.service.TeachingScheduleService;
import com.gr.smartedubackend.utils.ThrowUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 尘轩
 * @description 针对表【student(学生)】的数据库操作Service实现
 * @createDate 2025-07-01 15:42:32
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
        implements StudentService {

    @Resource
    private StudentGroupService studentGroupService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private TeachingScheduleService teachingScheduleService;

    @Override
    public QueryWrapper<Student> getQueryWrapper(StudentQueryRequest studentQueryRequest) {

        ThrowUtils.throwIf(studentQueryRequest == null, ErrorCode.PARAMS_ERROR);

        String studentNumber = studentQueryRequest.getStudentNumber();
        String studentName = studentQueryRequest.getStudentName();
        String className = studentQueryRequest.getClassName();
        Integer state = studentQueryRequest.getState();
        Date enrollmentTime = studentQueryRequest.getEnrollmentTime();
        String schoolName = studentQueryRequest.getSchoolName();
        String sortField = studentQueryRequest.getSortField();
        String sortOrder = studentQueryRequest.getSortOrder();

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(studentNumber), "studentNumber", studentNumber);
        queryWrapper.like(StrUtil.isNotEmpty(studentName), "studentName", studentName);
        queryWrapper.like(StrUtil.isNotEmpty(className), "className", className);
        queryWrapper.eq(ObjectUtil.isNotEmpty(state), "state", state);
        queryWrapper.eq(ObjectUtil.isNotEmpty(enrollmentTime), "enrollmentTime", enrollmentTime);
        queryWrapper.like(StrUtil.isNotEmpty(schoolName), "schoolName", schoolName);
        if (StrUtil.isNotEmpty(sortOrder) && StrUtil.isNotEmpty(sortField)) {
            queryWrapper.orderBy(true, sortOrder.equals("ascend"), sortField);
        } else {
            queryWrapper.orderByDesc(CommonConstant.CREATE_TIME);
        }

        return queryWrapper;
    }

    @Override
    public String updateClassStudentNum(StudentUpdateRequest studentUpdateRequest) {
        Student student = this.getById(studentUpdateRequest.getId());
        Long oldClassId = student.getClassId();
        Long classId = studentUpdateRequest.getClassId();
        if (classId == null || classId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        StudentGroup studentGroup = studentGroupService.getById(classId);
        if (studentGroup == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级不存在");
        }
        if (oldClassId != null && (long) oldClassId == classId) {
            return studentGroup.getClassName();
        }
        Integer studentNum = studentGroup.getStudentNum();
        studentGroup.setStudentNum(studentNum + 1);
        boolean result = studentGroupService.updateById(studentGroup);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        if (oldClassId != null) {
            StudentGroup oldStudentGroup = studentGroupService.getById(oldClassId);
            if (oldStudentGroup == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级不存在");
            }
            studentNum = oldStudentGroup.getStudentNum();
            oldStudentGroup.setStudentNum(studentNum - 1);
            result = studentGroupService.updateById(oldStudentGroup);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }
        return studentGroup.getClassName();
    }

    @Override
    public Page<Student> listStudentByPageByTeacher(StudentQueryByTeacherDto studentQueryByTeacherDto) {

        String teacherNumber = studentQueryByTeacherDto.getTeacherNumber();
        int current = studentQueryByTeacherDto.getCurrent();
        int pageSize = studentQueryByTeacherDto.getPageSize();
        String sortField = studentQueryByTeacherDto.getSortField();
        String sortOrder = studentQueryByTeacherDto.getSortOrder();
        Page<Student> studentPage = new Page<>(current, pageSize);
        // 查询教师id
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("teacherNumber", teacherNumber);
        Teacher teacher = teacherService.getOne(teacherQueryWrapper);
        ThrowUtils.throwIf(teacher == null, ErrorCode.NOT_FOUND_ERROR, "教师不存在");
        Long teacherId = teacher.getId();

        // 查询教师授课记录，再根据授课记录查询授课班级
        QueryWrapper<TeachingSchedule> teachingScheduleQueryWrapper = new QueryWrapper<>();
        teachingScheduleQueryWrapper.eq("teacherId", teacherId);
        List<TeachingSchedule> teachingScheduleList = teachingScheduleService.list(teachingScheduleQueryWrapper);
        if (teachingScheduleList.isEmpty()) {
            return studentPage;
        }
        Set<Long> classIdList = teachingScheduleList.stream().map(TeachingSchedule::getClassId).collect(Collectors.toSet());
        // 查询班级里的所有学生
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.in("classId", classIdList);
        if (StrUtil.isNotEmpty(sortOrder) && StrUtil.isNotEmpty(sortField)) {
            studentQueryWrapper.orderBy(true, sortOrder.equals("ascend"), sortField);
        } else {
            studentQueryWrapper.last("ORDER BY LEFT(studentName, 1) ASC");
        }

        return this.page(studentPage, studentQueryWrapper);
    }
}




